# -*- coding: utf-8 -*-

import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.gen

# from .websocket_setting import WS_SETTING

# from src.tornado_client import WebSocketClient
from src.websocket.api.api_home import ApiHomeHandler
from src.websocket.api.api_list import ApiListHandler
from src.websocket.api.api_read_file import ApiReadFileHandler
from src.websocket.api.api_reconn import ApiWebSocketReConn


class ClientHome(object):
    """
    处理websocket 服务器与客户端交互
    """

    clientRegister = {}

    def register(self, newer):
        # 获取所在服务
        server_home = str(newer.get_argument('service_env'))
        if server_home in self.clientRegister:
            self.clientRegister[server_home].append(newer)
        else:
            self.clientRegister[server_home] = [newer]

        # message = '加入聊天室（%s）' % serverHome
        # self.callbackTrigger(serverHome, message)

    def unregister(self, lefter):
        """
        客户端关闭连接，删除聊天室内对应的客户端连接实例
        """
        server_home = str(lefter.get_argument('service_env'))
        self.clientRegister[server_home].remove(lefter)
        # if self.clientRegister[serverHome]:
        #     message = '离开聊天室（%s）' % serverHome
        #     self.callbackTrigger(serverHome, message)

    def callbackNews(self, sender, message):
        """
        处理客户端提交的消息，发送给对应聊天室内所有的客户端
        """
        server_home = str(sender.get_argument('service_env'))
        self.callbackTrigger(server_home, message)

    def callbackTrigger(self, server_home, message):
        """
        消息触发器，将最新消息返回给对应聊天室的所有成员
        """
        for callbacker in self.clientRegister[server_home]:
            callbacker.write_message(message)


class EchoWebSocket(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        self.application.client_home.register(self)

    def on_message(self, message):
        self.application.client_home.callbackNews(self, message)

    def on_close(self):
        self.application.client_home.unregister(self)


class MyApplication(tornado.web.Application):
    def __init__(self, handlers=None):
        self.client_home = ClientHome()

        if handlers is None or len(handlers) <= 0:
            handlers = [
                ('/echo_ws', EchoWebSocket),
                ('/ws_reconn', ApiWebSocketReConn),
                ('/api_home', ApiHomeHandler),
                ('/api_list', ApiListHandler),
                ('/api_read_file', ApiReadFileHandler),
            ]

        settings = {
            'template_path': '',  # 'html',
            'static_path': ''  # 'static'
        }

        tornado.web.Application.__init__(self, handlers, **settings)


def main():
    tornado.options.parse_command_line()
    server = tornado.httpserver.HTTPServer(MyApplication())
    server.listen(5678)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    main()
